package com.twan.kotlinbase.util

import android.content.Context
import android.graphics.Bitmap
import android.widget.ImageView
import androidx.annotation.DrawableRes
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.twan.kotlinbase.R
import com.twan.kotlinbase.widgets.GlideRoundTransform
import java.util.concurrent.ExecutionException


object GlideUtils {
    fun load(context: Context?, view: ImageView?, url: String?) {
        Glide.with(context!!).load(url)
                .placeholder(R.mipmap.head_boy)
                .diskCacheStrategy(DiskCacheStrategy.ALL).into(view!!)
    }

    fun load(context: Context?, view: ImageView?, @DrawableRes placeholder: Int) {
        Glide.with(context!!).load(placeholder)
                .placeholder(R.mipmap.head_boy)
                .diskCacheStrategy(DiskCacheStrategy.ALL).into(view!!)
    }

    fun loadCicle(context: Context?, view: ImageView?, url: String?) {
        Glide.with(context!!).load(url)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .transform(GlideRoundTransform(context))
            .placeholder(R.mipmap.head_boy)
            .into(view!!)
    }

    fun load(context: Context?, view: ImageView?, url: String?, @DrawableRes placeholder: Int) {
        Glide.with(context!!).load(url)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .placeholder(placeholder).into(view!!)
    }

    fun loadCorner(context: Context, view: ImageView?, url: String?){
        var options=RequestOptions.bitmapTransform(RoundedCorners(5)) //图片圆角为20
        Glide.with(context).load(url)
                .apply(options)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .placeholder(R.mipmap.test).into(view!!)
    }

    //加载视频的第一帧,时间按微秒计算
    fun loadVideo0Frame(context: Context, view: ImageView, url: String?){
        Glide.with(context).setDefaultRequestOptions(
                RequestOptions().frame(1000000).centerCrop()).load(url).into(view)
    }

    fun loadBitmap(context: Context?, url: String?): Bitmap? {
        try {
            return Glide.with(context!!).asBitmap().load(url)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(
                        Target.SIZE_ORIGINAL,
                        Target.SIZE_ORIGINAL
                )
                .get()
        } catch (e: ExecutionException) {
            e.printStackTrace()
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }
        return null
    }
}